package com.example.qxfw.common.util;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 14559
 * @version 1.0
 * @description: TODO
 * @date 2024/12/10 18:49
 */
public class DocModelUtil {

    // 替换
    public static void replaceTextInParagraph(XWPFParagraph paragraph, String[] placeholders, String[] replacements) {
        String paragraphText = paragraph.getText();
        for (int i = 0; i < placeholders.length; i++) {
            String regex = Pattern.quote(placeholders[i]);
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(paragraphText);
            if (matcher.find()) {
                paragraphText = matcher.replaceAll(Matcher.quoteReplacement(replacements[i]));
            }
        }
        for (int i = 0; i < paragraph.getRuns().size(); i++) {
            if (i == 0) {
                paragraph.getRuns().get(i).setText(paragraphText, 0);
            } else {
                paragraph.getRuns().get(i).setText("", 0);
            }
        }
    }

    public static void insertImgToWord(XWPFParagraph paragraph, XWPFDocument document, MultipartFile imageFile) throws IOException, InvalidFormatException {
        //获取下标
        XmlCursor cursor = paragraph.getCTP().newCursor();
        XWPFParagraph newPara = document.insertNewParagraph(cursor);
        newPara.setAlignment(ParagraphAlignment.CENTER);//居中
        XWPFRun newParaRun = newPara.createRun();
        Image image = ImageIO.read(imageFile.getInputStream());
        int imageWidth = image.getWidth(null);  // 图片的原始宽度（像素）
        int imageHeight = image.getHeight(null); // 图片的原始高度（像素）
        // 获取Word文档页面的宽度
        // 默认情况下，Word页面宽度为8.5英寸（210mm），可以根据需要调整
        double pageWidthInInches = 480; // 默认页面宽度为8.5英寸
        int pageWidthInTwips = Units.toEMU(pageWidthInInches); // 转换为EMUs

        // 计算图片的新宽度和高度，保持比例
        // 设置图片宽度为页面宽度，自动调整高度
        int newWidth = pageWidthInTwips;
        int newHeight = (int) ((double) imageHeight / imageWidth * newWidth);
        newParaRun.addPicture(imageFile.getInputStream(), XWPFDocument.PICTURE_TYPE_PNG, "image.png,", newWidth, newHeight);
        document.removeBodyElement(document.getPosOfParagraph(paragraph));
    }

    /**
     * 设置单元格水平位置和垂直位置
     *
     * @param xwpfTable
     * @param verticalLoction    单元格中内容垂直上TOP，下BOTTOM，居中CENTER，BOTH两端对齐
     * @param horizontalLocation 单元格中内容水平居中center,left居左，right居右，both两端对齐
     */
    public static void setCellLocation(XWPFTable xwpfTable, String verticalLoction, String horizontalLocation) {
        java.util.List<XWPFTableRow> rows = xwpfTable.getRows();
        for (XWPFTableRow row : rows) {
            List<XWPFTableCell> cells = row.getTableCells();
            for (XWPFTableCell cell : cells) {
                CTTc cttc = cell.getCTTc();
                CTP ctp = cttc.getPList().get(0);
                CTPPr ctppr = ctp.getPPr();
                if (ctppr == null) {
                    ctppr = ctp.addNewPPr();
                }
                CTJc ctjc = ctppr.getJc();
                if (ctjc == null) {
                    ctjc = ctppr.addNewJc();
                }
                ctjc.setVal(STJc.Enum.forString(horizontalLocation)); //水平居中
                cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.valueOf(verticalLoction));//垂直居中
            }
        }
    }

    /**
     * 设置表格位置
     *
     * @param xwpfTable
     * @param location  整个表格居中center,left居左，right居右，both两端对齐
     */
    public static void setTableLocation(XWPFTable xwpfTable, String location) {
        CTTbl cttbl = xwpfTable.getCTTbl();
        CTTblPr tblpr = cttbl.getTblPr() == null ? cttbl.addNewTblPr() : cttbl.getTblPr();
        CTJc cTJc = tblpr.addNewJc();
        cTJc.setVal(STJc.Enum.forString(location));
    }
}
